using System;
using System.Collections.Generic;
using System.Windows.Forms;
using pal.SvnConf.Core;

namespace pal.SvnConf.GUI
{
    public partial class GroupMembershipEditor : UserControl
    {
        private readonly string _groupName;
        private readonly ISvnConfigurationProvider _configurationProvider;
        private MembershipChangeHandler _membershipUpdationHandler;
        private List<ISecurityPrincipal> _availableMembers = new List<ISecurityPrincipal>();
        private List<ISecurityPrincipal> _currentMembers = new List<ISecurityPrincipal>();

        public GroupMembershipEditor(string groupName, ISvnConfigurationProvider configurationProvider)
        {
            _groupName = groupName;
            _configurationProvider = configurationProvider;

            InitializeComponent();

            _availableMembers = _configurationProvider.AllMembers;
            _currentMembers = new List<ISecurityPrincipal>(_configurationProvider.FindGroupByName(groupName).Members);

            foreach (ISecurityPrincipal currentMember in _currentMembers)
                _availableMembers.Remove(currentMember);

            updateListData();
        }

        private void updateListData()
        {
//            _lstAvailableMembers.Items.Clear();
//            _lstCurrentMembers.Items.Clear();
            _lstAvailableMembers.DataSource = new List<ISecurityPrincipal>(_availableMembers);
            _lstCurrentMembers.DataSource = new List<ISecurityPrincipal>(_currentMembers);
        }

        private void OnUpdateMembershipClick(object sender, EventArgs e)
        {
            if (_membershipUpdationHandler != null)
                _membershipUpdationHandler(_groupName, _currentMembers);
        }

        public event MembershipChangeHandler OnMembershipChange
        {
            add { _membershipUpdationHandler += value; }
            remove { _membershipUpdationHandler -= value; }
        }

        private void OnAddMember(object sender, EventArgs e)
        {
            moveListItems(_lstAvailableMembers.SelectedItems, _availableMembers, _currentMembers);
            updateListData();
        }

        private void moveListItems(ListBox.SelectedObjectCollection itemsToMove, List<ISecurityPrincipal> from,
                                   List<ISecurityPrincipal> to)
        {
            foreach (ISecurityPrincipal securityPrincipal in itemsToMove)
            {
                to.Add(securityPrincipal);
                from.Remove(securityPrincipal);
            }
        }

        private void OnRemoveMemberClick(object sender, EventArgs e)
        {
            moveListItems(_lstCurrentMembers.SelectedItems, _currentMembers, _availableMembers);
            updateListData();
        }
    }

    public delegate void MembershipChangeHandler(string groupName, List<ISecurityPrincipal> members);
}